/**
 * Callback wrapping utility
 * https://github.com/npm/wrappy
 *
 * @param {Function} fn
 * @param {Function | null} cb
 * @return {(function(): *)|*}
 */
export default function wrappy (fn, cb = null) {
  if (fn && cb) return wrappy(fn)(cb)

  if (typeof fn !== 'function'){
    throw new TypeError('need wrapper function')
  }

  function wrapper() {
    const ret = fn.apply(this, arguments)
    const cb = arguments[arguments.length - 1]
    if (typeof ret === 'function' && ret !== cb) {
      Object.keys(cb).forEach(function (k) {
        ret[k] = cb[k]
      })
    }
    return ret
  }

  Object.keys(fn).forEach(function (k) {
    wrapper[k] = fn[k]
  })

  return wrapper
}
